//
//  KKComposeTextView.swift
//  KKWeibo
//
//  Created by kassia on 16/7/21.
//  Copyright © 2016年 kassia. All rights reserved.
//

import UIKit

class KKComposeTextView: UITextView {

   // 懒加载控件
    private lazy var placeHolderLable: UILabel = {
    
        let lable = UILabel()
        lable.font = UIFont.systemFontOfSize(12)
        lable.text = "听说下雨天☔️,很适合看书噢"
        // 多行显示
        lable.numberOfLines = 0
        lable.textColor = UIColor.lightGrayColor()
        return lable
    
    }()
    
    // 占位文字
    var placeHodel: String? {
    
        didSet {
        
          placeHolderLable.text = placeHodel
         }
    
    }
    
    // 重写text
    override var text: String? {
    
        didSet {
        
            placeHolderLable.hidden = hasText()
        
        }
    
    }
    
    
    // 重写字体大小
    override var font: UIFont? {
    
        didSet {
        
            if font == nil {
            
                return
            }
                placeHolderLable.font = font

        }
    
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        
        // 监听UIText文本的变化
        NSNotificationCenter.defaultCenter().addObserver(self,selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        
        addSubview(placeHolderLable)
        
        // 使用系统的自动布局方式
        placeHolderLable.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLable, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLable, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLable, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    
    }
    
    // 监听文字变化
    @objc private func textChange() {
    
        placeHolderLable.hidden = self.hasText()
    
    }
    
    // 移除通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
